/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.txweb.action;

import com.jspx.boot.environment.Environment;
import com.jspx.boot.sign.LanguageRes;
import com.jspx.txweb.IUserSession;
import com.jspx.txweb.annotation.HttpMethod;
import com.jspx.txweb.annotation.Operate;
import com.jspx.txweb.annotation.Safety;
import com.jspx.txweb.table.IUploadFile;
import com.jspx.txweb.view.UploadFileView;
import com.jspx.utils.ArrayUtil;
import com.jspx.utils.FileUtil;
import com.jspx.utils.StringUtil;
import java.io.File;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: chenyuan
 * Date: 12-12-4
 * Time: 下午2:34
 *
 */
@HttpMethod(caption="附件管理")
public class UploadFileManageAction extends UploadFileView {
    private Long[] idArray = null;
    @Safety(request = false)
    public void setIdArray(Long[] idArray) {
        this.idArray = idArray;
    }

    /**
     * 排序时间
     */
    @Operate(caption = "排序")
    public void sortDate() throws Exception {
        Long[] ids = getLongArray("id", idArray);
        if (ArrayUtil.isEmpty(ids)&&getId()>0) ids = new Long[]{getId()};
        if (ArrayUtil.isEmpty(ids)) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.needSelect));
            return;
        }
        if (uploadFileDAO.updateSortDate(ids)) {
            addActionMessage(language.getLang(LanguageRes.updateSuccess));
        } else addFieldInfo(Environment.warningInfo,language.getLang(LanguageRes.updateFailure));
    }


    /**
     * 提前
     */
    @Operate(caption = "提前")
    public void sortType() throws Exception {
        Long[] ids = getLongArray("id", idArray);
        if (ArrayUtil.isEmpty(ids)&&getId()>0) ids = new Long[]{getId()};
        if (ArrayUtil.isEmpty(ids)) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.needSelect));
            return;
        }
        if (uploadFileDAO.updateSortType(ids, getInt("sortType")))
        {
            addActionMessage(language.getLang(LanguageRes.updateSuccess));
            setActionResult(SUCCESS);
        } else addFieldInfo(Environment.warningInfo,language.getLang(LanguageRes.updateFailure));
    }


    @Operate(caption="删除")
    public void delete()
    {
        setActionResult(ROC);
        Long[] ids = getLongArray("id", idArray);
        if (ArrayUtil.isEmpty(ids)&&getId()>0) ids = new Long[]{getId()};
        if (ArrayUtil.isEmpty(ids)) {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.needSelect));
            return;
        }
        IUserSession userSession = (IUserSession) getUserSession();
        StringBuilder actionLog = new StringBuilder();
        try
        {
            for (long id : ids)
            {
                Object uploadFile = uploadFileDAO.get(id);
                if (uploadFile==null)
                {
                    addFieldInfo(Environment.warningInfo,language.getLang(LanguageRes.fileNotFind));
                    continue;
                }

                IUploadFile iUploadFile = (IUploadFile)uploadFile;
                deleteUploadFile(iUploadFile);
                actionLog.append(iUploadFile.getTitle()).append(" ").append(iUploadFile.getFileName()).append("<br>");


                //删除子文件，手机图片，缩图
               List childFile = (List)uploadFileDAO.getChildFileList(iUploadFile.getId());
               for (Object child:childFile)
               {
                   if (child==null)
                   {
                       addFieldInfo(Environment.warningInfo,language.getLang(LanguageRes.fileNotFind));
                       continue;
                   }
                   IUploadFile childUpload = (IUploadFile)child;
                   if (userSession.getUid()==childUpload.getPutUid())
                   {
                       deleteUploadFile(childUpload);
                       actionLog.append(childUpload.getTitle()).append(" ").append(childUpload.getFileName()).append("<br>");
                   }
               }
            }
            setActionLogContent(actionLog.toString());
            addActionMessage(language.getLang(LanguageRes.deleteSuccess));
        } catch (Exception e)
        {
            addFieldInfo(Environment.warningInfo,language.getLang(LanguageRes.deleteFailure));
            e.printStackTrace();
        }
    }

    private void deleteUploadFile(IUploadFile uploadFile) throws Exception {
        File deleteFile = UploadFileAction.getUploadFile(config,uploadFile.getFileName());
        if (uploadFileDAO.delete(uploadFile)>=0)
        {
            //确保没有其他人在使用文件
            if (!uploadFileDAO.haveHash(uploadFile.getHash())&&deleteFile!=null&&deleteFile.isFile())
            {
                //如果有缩图在删除缩图
                FileUtil.delete(deleteFile);

                File thumbnailFile = new File(deleteFile.getParentFile(),FileUtil.getThumbnailFileName(deleteFile.getName()));
                FileUtil.delete(thumbnailFile);

                File phoneImgFile = new File(deleteFile.getParentFile(),FileUtil.getMobileFileName(deleteFile.getName()));
                FileUtil.delete(phoneImgFile);
                //todo另外还要删除子图片
            }

        }
    }



    @Operate(caption="编辑")
    public void update() throws Exception {
        Object uploadFile =  getBean(uploadFileDAO.getClassType());
        IUploadFile iUploadFile = (IUploadFile)uploadFile;
        IUserSession userSession = (IUserSession) getUserSession();
        iUploadFile.setPutName(userSession.getName());
        iUploadFile.setPutUid(userSession.getUid());
        iUploadFile.setIp(getRemoteAddr());

        IUploadFile uploadFileOld = (IUploadFile) uploadFileDAO.get(iUploadFile.getId());
        if (uploadFileOld == null) {
            addFieldInfo(Environment.warningInfo,language.getLang(LanguageRes.invalidParameter) + ":" + iUploadFile.getId());
            setActionResult(ERROR);
            return;
        }
        if (StringUtil.isNULL(iUploadFile.getHash())) iUploadFile.setHash(uploadFileOld.getHash());
        iUploadFile.setCreateDate(uploadFileOld.getCreateDate());
        int x = uploadFileDAO.update(uploadFile);
        if (x > 0) {
            addActionMessage(language.getLang(LanguageRes.updateSuccess)+ ":" + x);
        } else {
            addFieldInfo(Environment.warningInfo, language.getLang(LanguageRes.updateFailure) + ":" + x);
        }
    }

    @Override
    public String execute() throws Exception
    {
        if (isMethodInvoked())
        {
            uploadFileDAO.evict(uploadFileDAO.getClassType());
        }
        return super.execute();
    }

}